import dayjs from "dayjs";
import { message } from "@/utils/message";
import { handleTree } from "@/utils/tree";
import { deepClone } from "@/utils/publicfunc";
// import { getUserList } from "@/api/system";
import { ElMessageBox, ElMessage } from "element-plus";
import { reactive, ref, computed, onMounted } from "vue";
import { myApplyList } from "@/api/flow/mydocuments";

export function mydocumentsHook() {
  const form = ref({});
  const eventform = reactive({});
  const dataList = ref([]);
  const treeData = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const selectionarr = ref([]);
  const pagetype = ref("list"); //list 列表页  //detail 详情页
  const mode = ref("create"); //create 新增  edit  check
  const dialogFlowVisible = ref(false);
  const pagination = ref({
    total: 0,
    pageSize: 10,
    pageNum: 1,
    background: true
  });
  //详情列表
  const detailform = ref({
    flowname: "",
    tablename: "",
    flowevent: [
      { eventname: "请假是申请单-审批完成事件" },
      { eventname: "请假是申请单-审批终止事件" }
    ],
    flowrange: true,
    bumen: ["技术中心"]
  });

  const rules = ref({
    flowname: [{ required: true, message: "请输入流程名称", trigger: "blur" }]
  });
  const eventrules = ref({
    eventname: [{ required: true, message: "请输入流程名称", trigger: "blur" }],
    version: [{ required: true, message: "请输入版本", trigger: "blur" }],
    port: [{ required: true, message: "请输入版本", trigger: "blur" }]
  });

  const columns: TableColumnList = [
    // {
    //   type: "selection",
    //   width: 55,
    //   align: "left",
    //   // hide: ({ checkList }) => !checkList.includes("勾选列")
    // },
    // {
    //   label: "序号",
    //   type: "index",
    //   minWidth: 70,
    //   // hide: ({ checkList }) => !checkList.includes("序号列")
    // },
    {
      label: "单号",
      prop: "formCode",
      align: "left"
    },
    {
      label: "单据标题",
      prop: "formTitle"
      // width: 150
    },
    {
      label: "表单名称",
      prop: "formName"
      // width: 150
    },
    {
      label: "当前审批节点",
      prop: "taskName"
      // width: 150
    },
    {
      label: "申请时间",
      prop: "createdTime"
      // width: 150
    },
    {
      label: "状态",
      prop: "processStatusName",
      cellRenderer: ({ row }) => {
        const color = {
          起草: "#D07AE8",
          审批中: "#0ABAFF",
          已终止: "#FD4242",
          审批完成: "#3BB61B",
          未审批: "#FFB81E"
        };
        const text = ["起草", "审批中", "已终止", "审批完成", "未审批"];
        const dom = (
          <div
            style={`background:${color[row.processStatusName]};`}
            class="radisinco"
          ></div>
        );
        return (
          <div class="rows">
            {dom}
            {row.processStatusName}
          </div>
        );
      }
      // width: 150
    },
    {
      label: "操作",
      fixed: "right",
      // width: 160,
      slot: "operation"
    }
  ];

  //========================================computed===================================================
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  //===========================================Mounted======================================================
  onMounted(() => {
    onSearch();
  });

  //========================================func===================================================

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message("已成功修改用户状态", {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function openflow() {
    dialogFlowVisible.value = true;
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    const selectdata = selectionarr.value;
    ElMessageBox.confirm(
      "请确认是否删除此流程，流程删除后如无对应流程，单据将无法提报，请知晓。",
      "删除流程",
      {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        type: "warning"
      }
    )
      .then(() => {
        ElMessage({
          type: "success",
          message: "Delete completed"
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "Delete canceled"
        });
      });
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    selectionarr.value = val;
    console.log("handleSelectionChange", selectionarr.value);
  }

  function deepClone(obj) {
    if (obj === undefined) {
      return undefined;
    }
    // set数据
    try {
      return JSON.parse(JSON.stringify(obj));
    } catch (e) {
      console.error("数据拷贝失败。deepClone：" + e);
    }
  }

  async function onSearch() {
    loading.value = true;
    const params = deepClone(form.value);
    if (Array.isArray(params.applyTime) && params.applyTime[0]) {
      params.applyTimeStart = params.applyTime[0];
      params.applyTimeEnd = params.applyTime[1];
    }
    params.pageNum = pagination.value.pageNum;
    params.pageSize = pagination.value.pageSize;
    console.log(params);
    const { data } = await myApplyList({ ...params });
    dataList.value = data.list;
    pagination.value.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  return {
    form,
    loading,
    columns,
    dataList,
    pagetype,
    mode,
    pagination,
    buttonClass,
    treeData,
    onSearch,
    resetForm,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,

    detailform,
    rules,
    dialogFlowVisible,
    openflow
  };
}
